package com.study.www.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author : 89007337.zhuyanpeng
 * @date :Create in  2019/8/19- 11:51
 **/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "test2EntityManagerFactory",
        transactionManagerRef = "test2TransactionManager",
        basePackages = {Test2JpaConfig.PACKAGES}
)
public class Test2JpaConfig {

    public static final String PACKAGES="com.study.www.test2";

    //ConfigurationProperties 根据配置文件进行截取匹配
    @Bean("test2DataSource")
    @ConfigurationProperties("spring.datasource.db2")
    public DataSource dateSource(){
        //jdbc
        //return DataSourceBuilder.create().build();
        // 阿里 druid
        return  DruidDataSourceBuilder.create().build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean test2EntityManagerFactory(EntityManagerFactoryBuilder builder){
        return builder
                .dataSource(dateSource())
                .packages(PACKAGES)
                .build();
    }

    @Bean
    PlatformTransactionManager test2TransactionManager(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(test2EntityManagerFactory(builder).getObject());
    }
}
